package com.bootdo.shop.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bootdo.common.config.WxMaConfiguration;
import com.bootdo.common.config.WxMaProperties;
import com.bootdo.common.utils.*;
import com.bootdo.shop.domain.WxShopCatAuditCategoryDO;
import com.bootdo.shop.domain.WxShopCatAuditResultDO;
import com.bootdo.shop.domain.WxShopCatDO;
import com.bootdo.shop.service.WxShopCatAuditCategoryService;
import com.bootdo.shop.service.WxShopCatAuditResultService;
import com.bootdo.shop.service.WxShopCatService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 类目资质申请表
 * 
 * @author long
 * @email 499626561@qq.com
 * @date 2021-05-19 14:24:51
 */
 
@Controller
@RequestMapping("/shop/wxShopCatAuditCategory")
public class WxShopCatAuditCategoryController {
	@Autowired
	private WxShopCatAuditCategoryService wxShopCatAuditCategoryService;
	@Autowired
	private WxMaProperties properties;
	@Autowired
	private WxShopCatAuditResultService wxShopCatAuditResultService;
	@Autowired
	private WxShopCatService wxShopCatService;
	
	@GetMapping()
	@RequiresPermissions("shop:wxShopCatAuditCategory:wxShopCatAuditCategory")
	String WxShopCatAuditCategory(){
	    return "shop/wxShopCatAuditCategory/wxShopCatAuditCategory";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("shop:wxShopCatAuditCategory:wxShopCatAuditCategory")
	public PageUtils list(@RequestParam Map<String, Object> params){
	    params.put("delFlag","0");
	    params.put("sort","ca_at");
	    params.put("order","desc");
        //查询列表数据
        Query query = new Query(params);
		final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
	    if(params.containsKey("name")&&StringUtils.isNotBlank(params.get("name").toString())){
            List<WxShopCatAuditCategoryDO> wxShopCatAuditCategoryList = wxShopCatAuditCategoryService.likeList(query);
			List<Map<String,Object>> list = new ArrayList<>();
			if(wxShopCatAuditCategoryList.size()>0){

				for (WxShopCatAuditCategoryDO wxShopCatAuditCategoryDO : wxShopCatAuditCategoryList) {
					WxShopCatAuditResultDO wxShopCatAuditResultDO = wxShopCatAuditResultService.getByCategoryId(wxShopCatAuditCategoryDO.getId());
					Map<String, Object> stringObjectMap = BeanUtil.beanToMap(wxShopCatAuditCategoryDO);
					stringObjectMap.put("status",wxShopCatAuditResultDO.getStatus());
					stringObjectMap.put("reason",wxShopCatAuditResultDO.getRejectReason());
					WxShopCatDO wxShopCatDO = wxShopCatService.getByThirdCatId(wxShopCatAuditCategoryDO.getLevel3());
					stringObjectMap.put("level1",wxShopCatDO.getFirstCatName());
					stringObjectMap.put("level2",wxShopCatDO.getSecondCatName());
					stringObjectMap.put("level3",wxShopCatDO.getThirdCatName());
					if(wxShopCatAuditResultDO!=null && wxShopCatAuditResultDO.getStatus()!=1){
						try {
							//同步审核结果
							Map<String,Object> resultMap = new HashMap<>();
							resultMap.put("audit_id",wxShopCatAuditResultDO.getAuditId());
							String post = wxService.post("https://api.weixin.qq.com/shop/audit/result", resultMap);
							JSONObject jsonObject = JSONUtil.parseObj(post);
							if(jsonObject.getInt("errcode")==0){
								JSONObject data = jsonObject.getJSONObject("data");
								wxShopCatAuditResultDO.setRejectReason(data.getStr("reject_reason"));
								wxShopCatAuditResultDO.setStatus(data.getInt("status"));
								wxShopCatAuditResultDO.setUpAt(new Date());
								wxShopCatAuditResultService.update(wxShopCatAuditResultDO);
								stringObjectMap.put("status",wxShopCatAuditResultDO.getStatus());
								stringObjectMap.put("reason",wxShopCatAuditResultDO.getRejectReason());
							}

						} catch (WxErrorException e) {
							e.printStackTrace();
						}



					}
					list.add(stringObjectMap);
				}
			}
            int total = wxShopCatAuditCategoryList.size();
            PageUtils pageUtils = new PageUtils(list, total);
            return pageUtils;
		}

		List<WxShopCatAuditCategoryDO> wxShopCatAuditCategoryList = wxShopCatAuditCategoryService.list(query);
		List<Map<String,Object>> list = new ArrayList<>();
	    if(wxShopCatAuditCategoryList.size()>0){

			for (WxShopCatAuditCategoryDO wxShopCatAuditCategoryDO : wxShopCatAuditCategoryList) {
				WxShopCatAuditResultDO wxShopCatAuditResultDO = wxShopCatAuditResultService.getByCategoryId(wxShopCatAuditCategoryDO.getId());
				Map<String, Object> stringObjectMap = BeanUtil.beanToMap(wxShopCatAuditCategoryDO);
				stringObjectMap.put("status",wxShopCatAuditResultDO.getStatus());
				stringObjectMap.put("reason",wxShopCatAuditResultDO.getRejectReason());
				WxShopCatDO wxShopCatDO = wxShopCatService.getByThirdCatId(wxShopCatAuditCategoryDO.getLevel3());
				stringObjectMap.put("level1",wxShopCatDO.getFirstCatName());
				stringObjectMap.put("level2",wxShopCatDO.getSecondCatName());
				stringObjectMap.put("level3",wxShopCatDO.getThirdCatName());
				list.add(stringObjectMap);
				if(wxShopCatAuditResultDO!=null && wxShopCatAuditResultDO.getStatus()!=1){
					try {
						//同步审核结果
						Map<String,Object> resultMap = new HashMap<>();
						resultMap.put("audit_id",wxShopCatAuditResultDO.getAuditId());
						String post = wxService.post("https://api.weixin.qq.com/shop/audit/result", resultMap);
						JSONObject jsonObject = JSONUtil.parseObj(post);
						if(jsonObject.getInt("errcode")==0){
							JSONObject data = jsonObject.getJSONObject("data");
							wxShopCatAuditResultDO.setRejectReason(data.getStr("reject_reason"));
							wxShopCatAuditResultDO.setStatus(data.getInt("status"));
							wxShopCatAuditResultDO.setUpAt(new Date());
							wxShopCatAuditResultService.update(wxShopCatAuditResultDO);
							stringObjectMap.put("status",wxShopCatAuditResultDO.getStatus());
							stringObjectMap.put("reason",wxShopCatAuditResultDO.getRejectReason());
						}

					} catch (WxErrorException e) {
						e.printStackTrace();
					}



				}
			}
		}
		int total = wxShopCatAuditCategoryService.count(query);
		PageUtils pageUtils = new PageUtils(list, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("shop:wxShopCatAuditCategory:add")
	String add(){
	    return "shop/wxShopCatAuditCategory/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("shop:wxShopCatAuditCategory:edit")
	String edit(@PathVariable("id") String id,Model model){
		WxShopCatAuditCategoryDO wxShopCatAuditCategory = wxShopCatAuditCategoryService.get(id);
		model.addAttribute("wxShopCatAuditCategory", wxShopCatAuditCategory);
	    return "shop/wxShopCatAuditCategory/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("shop:wxShopCatAuditCategory:add")
	public R save( WxShopCatAuditCategoryDO wxShopCatAuditCategory){
	    wxShopCatAuditCategory.setId(UuidUtil.get32UUID());
	    wxShopCatAuditCategory.setDelFlag(0);
	    wxShopCatAuditCategory.setCaAt(new Date());

		WxShopCatDO wxShopCatDO = wxShopCatService.getByThirdCatId(wxShopCatAuditCategory.getLevel3());

	    //上传类目资质
		try {
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			Map<String,Object> categoryMap = new HashMap<>();
			Map<String,Object> auditReqMap = new HashMap<>();
			auditReqMap.put("license",wxShopCatAuditCategory.getLicense());
			Map<String,Object> categoryInfomap = new HashMap<>();
			categoryInfomap.put("level1",wxShopCatDO.getFirstCatId());
			categoryInfomap.put("level2",wxShopCatDO.getSecondCatId());
			categoryInfomap.put("level3",wxShopCatAuditCategory.getLevel3());
			categoryInfomap.put("certificate",wxShopCatAuditCategory.getCertificate());
			auditReqMap.put("category_info",categoryInfomap);
			categoryMap.put("audit_req",auditReqMap);
			String post = wxService.post("https://api.weixin.qq.com/shop/audit/audit_category", categoryMap);
			JSONObject jsonObject = JSONUtil.parseObj(post);
			if(jsonObject.getInt("errcode")==0){
				String audit_id = jsonObject.getStr("audit_id");
				WxShopCatAuditResultDO wxShopCatAuditResultDO = new WxShopCatAuditResultDO();
				wxShopCatAuditResultDO.setAuditId(audit_id);
				wxShopCatAuditResultDO.setCategoryId(wxShopCatAuditCategory.getId());
				wxShopCatAuditResultDO.setStatus(0);
				wxShopCatAuditResultDO.setCaAt(new Date());
				wxShopCatAuditResultDO.setId(UuidUtil.get32UUID());
				wxShopCatAuditResultDO.setDelFlag(0);
				wxShopCatAuditResultService.save(wxShopCatAuditResultDO);
				wxShopCatAuditCategoryService.save(wxShopCatAuditCategory);
				return R.ok();
			}else{
				//throw new WxErrorException(WxError.fromJson(post, WxType.MiniApp));
				return R.error(jsonObject.getStr("errmsg"));
			}
		} catch (WxErrorException e) {
			if(e.getError().getErrorCode()==1050003){
				return R.error("该类目已审核通过或无需申请，无需重复申请");
			}
			return R.error();
		}



	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("shop:wxShopCatAuditCategory:edit")
	public R update( WxShopCatAuditCategoryDO wxShopCatAuditCategory){
		wxShopCatAuditCategory.setUpAt(new Date());


		//上传类目资质
		try {
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			Map<String,Object> categoryMap = new HashMap<>();
			Map<String,Object> auditReqMap = new HashMap<>();
			auditReqMap.put("license",wxShopCatAuditCategory.getLicense());
			Map<String,Object> categoryInfomap = new HashMap<>();
			categoryInfomap.put("level1",wxShopCatAuditCategory.getLevel1());
			categoryInfomap.put("level2",wxShopCatAuditCategory.getLevel2());
			categoryInfomap.put("level3",wxShopCatAuditCategory.getLevel3());
			categoryInfomap.put("certificate",wxShopCatAuditCategory.getCertificate());
			auditReqMap.put("category_info",categoryInfomap);
			categoryMap.put("audit_req",auditReqMap);
			String post = wxService.post("https://api.weixin.qq.com/shop/audit/audit_category", categoryMap);
			JSONObject jsonObject = JSONUtil.parseObj(post);
			if(jsonObject.getInt("errcode")==0){
				String audit_id = jsonObject.getStr("audit_id");
				WxShopCatAuditResultDO wxShopCatAuditResultDO = new WxShopCatAuditResultDO();
				wxShopCatAuditResultDO.setAuditId(audit_id);
				wxShopCatAuditResultDO.setCategoryId(wxShopCatAuditCategory.getId());
				wxShopCatAuditResultDO.setStatus(0);
				wxShopCatAuditResultDO.setCaAt(new Date());
				wxShopCatAuditResultDO.setDelFlag(0);
				wxShopCatAuditResultDO.setId(UuidUtil.get32UUID());
				wxShopCatAuditResultService.save(wxShopCatAuditResultDO);

				wxShopCatAuditCategoryService.update(wxShopCatAuditCategory);
				return R.ok();
			}else{
				return R.error(jsonObject.getStr("errmsg"));
			}
		} catch (WxErrorException e) {
			if(e.getError().getErrorCode()==1050003){
				return R.error("该类目已审核通过，无需重复申请");
			}

			e.printStackTrace();
			return R.error();
		}

	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("shop:wxShopCatAuditCategory:remove")
	public R remove( String id){
		WxShopCatAuditCategoryDO wxShopCatAuditCategory = wxShopCatAuditCategoryService.get(id);
		wxShopCatAuditCategory.setDelFlag(1);
		wxShopCatAuditCategory.setUpAt(new Date());
		if(wxShopCatAuditCategoryService.update(wxShopCatAuditCategory)>0){
		return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("shop:wxShopCatAuditCategory:batchRemove")
	public R remove(@RequestParam("ids[]") String[] ids){
	   if(ids.length>0){
			for (String string : ids) {
				WxShopCatAuditCategoryDO wxShopCatAuditCategory = wxShopCatAuditCategoryService.get(string);
				wxShopCatAuditCategory.setDelFlag(1);
				wxShopCatAuditCategory.setUpAt(new Date());
				wxShopCatAuditCategoryService.update(wxShopCatAuditCategory);
			}
		}
	
		return R.ok();
	}
	
}
